package com.shebao.utils;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class FileUtil {
	
	@Value("${file.outFile}")
	private String outFile;
	
	public byte[] read(String path){
		File f = new File(path);  
        if (!f.exists()) {  
            throw new RuntimeException("读取文件失败！"); 
        }  
        FileChannel channel = null;  
        FileInputStream fs = null;  
        try {  
            fs = new FileInputStream(f);  
            channel = fs.getChannel();  
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());  
            while ((channel.read(byteBuffer)) > 0) {  
                // do nothing  
                // System.out.println("reading");  
            }  
            return byteBuffer.array();  
        } catch (Exception e) {  
        	throw new RuntimeException("读取文件失败！"); 
        } finally {  
            try {  
                channel.close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            try {  
                fs.close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
	}
	
	
	public void deleteFile(String path) {
        File file = new File(path);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
        	file.delete();
        } 
    }
	
	public void cleanFile(){
		File file=new File(outFile);
		if (file.isDirectory()) {
			String[] children = file.list();
			for(String s:children){
				if(s.endsWith("pdf")){
					deleteFile(outFile+s);
				}
			}
		}
	}
}
